package bluetoothCommunication;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

public class BTCommandWrapper {
	private ArrayList<Integer> values= new ArrayList<Integer>();

	private DataInputStream dis;
	private DataOutputStream dos;
    private DisWrap gdisw;
    public List<Integer> blackList=new ArrayList<Integer>();
    private boolean isPressed=false;
    
    //-1 = end of barcode
    private LinkedBlockingQueue<Integer> barcodeQueue = new LinkedBlockingQueue<Integer>();
    
    private Object barcodeLock = new Object();
    
    public BTCommandWrapper(BTConnection conn)
    {
    	gdisw = conn.GetDisWrap();	
    }
	
	public void SendCommand(byte b, int value)
	{		
        dos=gdisw.getDos();
        
//		System.out.println("Sending Command: " +b);
		try {
			dos.writeByte(b);
			dos.writeInt(value);
			dos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String receiveBarcodeData()
	{
		String output = "";
		// Return first from buffer
		if(!queueContainsBarcode())
			return output;
		
		synchronized(barcodeLock)
		{
			int reading= removeFirstFromBCQueue();
			
			// -1 = end of barcode
			while (reading != -1) {
				output += Character.toString((char)reading);
				reading = removeFirstFromBCQueue();
			}

			System.out.println(output);
			
			return output;
		}
	}
	
	private int removeFirstFromBCQueue() {
		return barcodeQueue.remove();
	}

	private boolean queueContainsBarcode() {
		return barcodeQueue.size() > 8;
	}

	public synchronized int SendCommandAndReceive(Command c, int value)
	{
		SendCommand(c.value(), value);
		
		return receive();
	}
	public int receiveValue(){
//		receive();
		if (values.isEmpty())
			return -1;
		
		return values.remove(0);
	}
		
	
	private int receive()
	{		
		dis = gdisw.getDis();
		
		try {			
			byte code = dis.readByte();			
			int data = dis.readInt();
			
//			System.out.println("Received code: "+code+ " data: "+ data);
		
		if (code == DataType.BARCODE.value())
		{
			// add data to barcode buffer
			synchronized(barcodeLock)
			{
				try {
					if(barcodeQueue.contains(-1))
						barcodeQueue.clear();
					barcodeQueue.put(data);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}	
			return receive();
		}
		if (code == DataType.TESTDATA.value()){
			values.add(data);
			return receive();
		}
		if(code==DataType.FOUNDBLACK.value()){
			blackList.add(data);
			return receive();
		}
		if(code==DataType.ISPRESSED.value()){
			setPressed(true);
			return receive();
		}
			
		return data;
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return -1;		
	}

	public boolean isPressed() {
		return isPressed;
	}

	public void setPressed(boolean isPressed) {
		this.isPressed = isPressed;
	}
	

}
